import numpy as np 
import json
import pandas as pd   
import random, csv
from random import choice
import argparse


'''
距离混淆矩阵

'''
distance = {'下渚湖国家湿地':[0,20.8,18.7,21.6,24.9,29.8,26.2,27.6,28.2,26,31.4,34.3,29],
            '东明山森林公园':[20.8,0,36.9,39.2,42.4,47.3,43.1,45.1,45.7,43.4,48.5,51.4,45.4],
            '蚕乐谷':[18.7,36.9,0,2.7,6,10.9,7.3,8.7,9.3,7,9.3,13.7,42.9],
            '庾村':[21.6,39.2,2.7,0,3.5,8.4,4.8,6.2,6.8,5.8,8,12.5,45.3],
            '旭光台':[24.9,42.4,6,3.5,0,1.1,1.3,2.7,3.7,9.1,11.3,13.7,48.8],
            '松月庐':[29.8,47.3,10.9,8.4,1.1,0,1.5,2.8,2.6,13.9,16.2,14.3,53.6],
            '芦花荡公园':[26.2,43.1,7.3,4.8,1.3,1.5,0,1.4,4.1,10.4,12.7,12.1,50.1],
            '剑池':[27.6,45.1,8.7,6.2,2.7,2.8,1.4,0,5.4,11.7,19.7,22,51.4],
            '莫干山大坑景区':[28.2,45.7,9.3,6.8,3.7,2.6,4.1,5.4,0,12.4,14.7,16.1,52.1],
            '裸心堡':[26,43.4,7,5.8,9.1,13.9,10.4,11.7,12.4,0,2.3,10,57.2],
            '三九坞':[31.4,48.5,9.3,8,11.3,16.2,12.7,19.7,14.7,2.3,0,12.3,55.2],
            '德清后坞村景区':[34.3,51.4,13.7,12.5,13.7,14.3,12.1,22,16.1,10,12.3,0,58.2],
            '新市古镇':[29,45.4,42.9,45.3,48.8,53.6,50.1,51.4,52.1,57.2,55.2,58.2,0]
           }

'''
spots 风景区
restaurants 餐厅
restaurantsAreas 餐厅所在区域
usrcity 用户来源地 0~684


'''
spots = pd.read_csv("./route_generator/spots.csv")           	
restaurants = pd.read_csv("./route_generator/meishi-jsonFile.csv")
restaurantsAreas = np.unique(restaurants['areaName'])
hotel = pd.read_csv("./route_generator/hotel.csv")
relax = pd.read_csv('./route_generator/xiuxianyule.csv')  
usrcity = pd.read_csv('./route_generator/from(province).csv')

def selectrestaurants(spotvalue1, restaurants, avgpricevalue):
    '''
    靠近第一个景区的美食
    spotvalue1 == 4-8 10-11 莫干山风景区 洋家乐
    spotvalue1 == 2-3 9 莫干山 洋家乐
    spotvalue1 == 1    三合乡13km 19min, 
    spotvalue1 == 12    新市镇 河滨公园 1.3km
    spotvalue1 == 0    春晖公园11.2km 德清县10.8km 德清县中心城区10km 汇丰广场10.7km 开发区11km 康乐小区11.9km 
                        蓝色港湾9.8km  科技新城11km 18min 群安小区 12.2km 20min 私营城14km 23min 沃尔玛12.6km 19min
                        武康镇10.4km 17min 营盘小区11km 17min 永安小区11.4km 18min 余英坊12km 18min 下渚湖
                        雷甸镇 12.7km 18min
                        乾元镇 6.2km 10min 
                        三合乡 7.9km 11min
                        禹越镇 29.1km 38min
                        河滨公园 28.1km 37min

    '''
    restaurantareaName = np.array(restaurants['areaName'])
    restaurantindex = []
    if spotvalue1 == 12:
        restaurantindex1 = np.argwhere(restaurantareaName=='新市镇')
        restaurantindex2 = np.argwhere(restaurantareaName=='河滨公园')
        restaurantindex = np.append(restaurantindex1,restaurantindex2)
    elif spotvalue1 == 1:
        restaurantindex = []
        restaurantindex1 = np.argwhere(restaurantareaName=='三合乡')
        restaurantindex = np.append(restaurantindex,restaurantindex1)
    elif spotvalue1 == 2 or spotvalue1 == 3 or spotvalue1 == 9:
        restaurantindex1 = np.argwhere( restaurantareaName=='莫干山')
        restaurantindex2 = np.argwhere( restaurantareaName=='洋家乐')
        restaurantindex = np.append(restaurantindex1,restaurantindex2)
    elif (spotvalue1 >= 4 and spotvalue1 <= 8) or (spotvalue1 >= 10 and spotvalue1 <= 11):
        restaurantindex1 = np.argwhere( restaurantareaName=='莫干山风景区')
        restaurantindex2 = np.argwhere( restaurantareaName=='洋家乐')
        restaurantindex = np.append(restaurantindex1,restaurantindex2)
    elif spotvalue1 == 0:
        areaNAMEs = ['春晖公园', '德清县', '德清县中心城区', '汇丰广场', '开发区', '康乐小区', 
                    '蓝色港湾', '科技新城', '群安小区', '私营城', '沃尔玛', '武康镇', '营盘小区',
                    '永安小区', '余英坊', '下渚湖', '雷甸镇', '乾元镇', '三合乡']
        restaurantindex = [ ]
        for areaNAME in areaNAMEs:
            restaurantindex1 = np.argwhere( restaurantareaName == areaNAME)
            restaurantindex = np.append(restaurantindex, restaurantindex1)
    '''
    根据平均消费，决定饭店地址
    '''
    if avgpricevalue <= 2000:
        place2index1 = list(restaurants['avgPrice'][restaurants['avgPrice']<50].index)
    elif avgpricevalue <= 3500:
        place2index1 = list(restaurants['avgPrice'][restaurants['avgPrice']<100].index)
    else:
        place2index1 = list(restaurants['avgPrice'][restaurants['avgPrice']>100].index)
    place2index = list(set(restaurantindex).intersection(set(place2index1)))
        # print(len(place2index1), len(restaurantindex), len(place2index))
    try:
        place2value = choice(place2index)
    except:
        place2value = choice(restaurantindex)
    return place2value

def selectrelax(spotvalue1, relax, avgpricevalue):
    '''
    靠近第一个景区的美食
    spotvalue1 == 4-8 10-11 莫干山风景区 洋家乐
    spotvalue1 == 2-3 9     莫干山 洋家乐
    spotvalue1 == 1         三合乡13km 19min, 
    spotvalue1 == 12        新市镇 河滨公园 1.3km
    spotvalue1 == 0         春晖公园11.2km 德清县10.8km 德清县中心城区10km 汇丰广场10.7km 开发区11km 康乐小区11.9km 
                            蓝色港湾9.8km  科技新城11km 18min 群安小区 12.2km 20min 私营城14km 23min 沃尔玛12.6km 19min
                            武康镇10.4km 17min 营盘小区11km 17min 永安小区11.4km 18min 余英坊12km 18min 下渚湖
                            雷甸镇 12.7km 18min
                            乾元镇 6.2km 10min 
                            三合乡 7.9km 11min
                            禹越镇 29.1km 38min
                            河滨公园 28.1km 37min

    '''
    relaxareaName = np.array(relax['area'])
    relaxindex = []
    if spotvalue1 == 12:
        relaxindex1 = np.argwhere(relaxareaName=='新市镇')
        relaxindex2 = np.argwhere(relaxareaName=='河滨公园')
        relaxindex = np.append(relaxindex1,relaxindex2)
    elif spotvalue1 == 1:
        return random.randrange(0,55,1)
    elif spotvalue1 >= 2 and spotvalue1 <= 11:
        relaxindex = []
        relaxindex1 = np.argwhere( relaxareaName=='莫干山')
        relaxindex = np.append(relaxindex,relaxindex1)
    elif spotvalue1 == 0:
        areaNAMEs = ['德清', '德清县中心城区', '汇丰广场', '开发区',
                    '科技新城', '群安小区', '私营城', '沃尔玛', '武康镇', '营盘小区',
                    '永安小区', '余英坊']
        relaxindex = [ ]
        for areaNAME in areaNAMEs:
            relaxindex1 = np.argwhere( relaxareaName == areaNAME)
            relaxindex = np.append(relaxindex, relaxindex1)
    '''
    根据平均消费，决定饭店地址
    '''
    if avgpricevalue <= 2000:
        place2index1 = list(relax['avgprice'][relax['avgprice']<100].index)
    elif avgpricevalue <= 3500:
        place2index1 = list(relax['avgprice'][relax['avgprice']<150].index)
    else:
        place2index1 = list(relax['avgprice'][relax['avgprice']>100].index)
    place2index = list(set(relaxindex).intersection(set(place2index1)))
        # print(len(place2index1), len(relaxindex), len(place2index))
    try:
        place2value = choice(place2index)
    except:
        place2value = choice(relaxindex)
    return place2value

def selectplace3(distance,spots,spotvalue1,rangevalue):
    disfrom1 = np.array(distance[spots['景点'][spotvalue1]])
    if rangevalue == 0:
        spot2index = np.argwhere(disfrom1 < 10)
    elif rangevalue == 1:
        spot2index = np.argwhere(disfrom1 < 20)
    elif rangevalue == 2:
        spot2index = np.argwhere(disfrom1 < 40)
    elif rangevalue == 3:
        spot2index = np.argwhere(disfrom1 < 100)
    
    spotvalue2 = choice(spot2index)[0]
    # print(disfrom1, rangevalue, spot2index, spotvalue2, spotvalue1)
    return spotvalue2


def get_args():
    parser = argparse.ArgumentParser(description='Predict masks from input images',
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('--input', '-i', metavar='INPUT', nargs='+',
                        help='filenames of input images', required=True)

    return parser.parse_args()

# avgpricevalue, rangevalue, spotvalue1
def run(avgpricevalue, rangevalue, spotvalue1):
    result = []
    result.append(spots['景点'][spotvalue1])

    if spotvalue1 == 13:
        place2value = selectrestaurants(0, restaurants, avgpricevalue)
    else:
        place2value = selectrestaurants(spotvalue1, restaurants, avgpricevalue)
    result.append(restaurants['name'][place2value])
    '''
    结合第一个景点和可接受距离，找到第二个景点
    acceptablerange = ['0~10km', '10~20km', '20~40km', '40km以上']
    ''' 
    spotvalue2 = selectplace3(distance,spots,spotvalue1,rangevalue)
    limit = 5
    while spotvalue2 == spotvalue1 and limit < 0:
        spotvalue2 = selectplace3(distance,spots,spotvalue1,rangevalue)
        limit = limit - 1
    while spotvalue2 == spotvalue1:
        spotvalue2 = random.randrange(0,13,1)
    if spotvalue2 == 13:
        result.append(spots['景点'][0])
    else:
        result.append(spots['景点'][spotvalue2])
    '''
    第一天住宿酒店
    '''
    place4value = random.randrange(0,1057,1)
    result.append(hotel['name'][place4value])
    '''
    第二天景点
    '''
    spotvalue3 = selectplace3(distance,spots,spotvalue2,rangevalue)
    limit = 5
    while (spotvalue3 == spotvalue1 or spotvalue3 == spotvalue2) and (limit < 0):
        spotvalue3 = selectplace3(distance,spots,spotvalue2,rangevalue)
        limit = limit - 1
    while spotvalue3 == spotvalue1 or spotvalue3 == spotvalue2:
        spotvalue3 = random.randrange(0,13,1)
    if spotvalue3 == 13:
        result.append(spots['景点'][0])
    else:
        result.append(spots['景点'][spotvalue3])
    '''
    第二天餐厅
    '''
    if spotvalue3 == 13:
        place6value = selectrestaurants(0, restaurants, avgpricevalue)
    else:
        place6value = selectrestaurants(spotvalue3, restaurants, avgpricevalue)
    result.append(restaurants['name'][place6value])
    # place6value = random.randrange(0,3268,1)
    # result['place6'] = restaurants['name'][place6value]
    '''
    休闲娱乐场所
    '''
    if spotvalue3 == 13:
        place7value = selectrelax(0, relax, avgpricevalue)
    else:
        place7value = selectrelax(spotvalue3, relax, avgpricevalue)
    result.append(relax['name'][place7value])

    '''
    酒店
    '''
    place8value = random.randrange(0,1057,1)
    result.append(hotel['name'][place8value])
   
    return result


import networkx as nx
import matplotlib.pyplot as plt
import random
from tools.common_function import *

# Windows去除中文乱码
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号

def genRouteFig(avgpricevalue, rangevalue, spotvalue1):
    G = nx.MultiDiGraph()
    path = run(1924,0,7)

    for i, p in enumerate(path[1:]):
        G.add_edge(path[i], p)
    nx.draw(G, with_labels=True)
    hash_id = genUniqueId()
    plt.savefig("static/route_img/{}.png".format(hash_id))

    return hash_id

if __name__ == '__main__':
    # print(run(1924,0,7))
    genRouteFig(1924,0,7)


